package banner

import (
	"context"
	"strconv"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetBannerByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetBannerByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetBannerByIdLogic {
	return &BackendGetBannerByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetBannerByIdLogic) BackendGetBannerById(in *backend.IDReq) (*backend.BannerInfo, error) {
	if in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	res, err := l.svcCtx.Banner.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	mediaFilterMap := make(map[string]map[string][]any)
	mediaFilterMap[model.AttachmentRelationshipColumns.ObjectID] = map[string][]any{
		"equalTo": []any{in.Id},
	}
	mediaFilterMap[model.AttachmentRelationshipColumns.ObjectType] = map[string][]any{
		"equalTo": []any{globalkey.AttachmentLogTypeBanner},
	}
	mediaList, _, err := l.svcCtx.Banner.GetMedia(l.ctx, model.M{}, -1, mediaFilterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var media []*backend.MediaInfo
	for _, v := range mediaList {
		media = append(media, &backend.MediaInfo{
			Uid:       &v.RelationshipID,
			Id:        pointy.GetPointer(strconv.FormatInt(int64(v.AttachmentID), 10)),
			Thumbnail: pointy.GetPointer(uint32(v.AttachmentThumbnail)),
			Order:     pointy.GetPointer(uint32(v.AttachmentOrder)),
			Uri:       &v.AttachmentImageSource,
			Url:       &v.AttachmentImageURL,
			AltText:   &v.AttachmentImageAlt,
			MetaData:  &v.AttachmentImageMeta,
		})
	}

	var sort *uint32
	if res.Sort != uint16(globalkey.SystemDefaultSort) {
		sort = pointy.GetPointer(uint32(res.Sort))
	}

	return &backend.BannerInfo{
		Id:        &res.ID,
		PicId:     &res.PicID,
		PicUrl:    &res.PicURL,
		Type:      pointy.GetPointer(uint32(res.Type)),
		Title:     &res.Title,
		LinkType:  pointy.GetPointer(uint32(res.LinkType)),
		LinkUrl:   &res.LinkURL,
		AdType:    pointy.GetPointer(uint32(res.ObjectType)),
		AdId:      &res.ObjectID,
		Status:    pointy.GetPointer(uint32(res.Status)),
		Sort:      sort,
		CreatedAt: pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt: pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
		DeletedAt: pointy.GetPointer(modelx.FormatNullDotTime(res.DeletedAt, "")),
		StartedAt: pointy.GetPointer(modelx.FormatNullDotTime(res.StartedAt, "")),
		EndedAt:   pointy.GetPointer(modelx.FormatNullDotTime(res.EndedAt, "")),
		Media:     media,
	}, nil
}
